package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Cacheable(cacheNames={"category"},key = "'TestRedis'")
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(StringUtils.isEmpty(catalogJson)){
            Map<String, List<Catalog2Vo>> map = getCatalogJsonFromDB();
            // redis中存储的类型为<String,String>,因此,需要将java对象转变为json
            String jsonString = JSON.toJSONString(map);
            redisTemplate.opsForValue().set("catalogJson",jsonString);
            return map;
        }
        // 查出的是json,因此,需要将json转化为java对象返回
        Map<String, List<Catalog2Vo>> parseObject = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>(){});
        return parseObject;
    }

    public Map<String, List<Catalog2Vo>> getCatalogJsonFromFENBUSHILockDB() {
        RLock lock = redissonClient.getLock("catalogJson-lock");
        Map<String,List<Catalog2Vo>> map;
        lock.lock();
        try {
            map = getStringListMap();
        }finally {
            lock.unlock();
        }
        return map;
    }
    public Map<String, List<Catalog2Vo>> getCatalogJsonFromDB() {
        String uuid = UUID.randomUUID().toString();
        // 1.抢占分布式锁即去redis中抢占坑位
        Boolean absent = redisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if(absent){
            // 2.抢占成功
            System.out.println("抢占分布式锁成功...");
            // 执行业务
            Map<String, List<Catalog2Vo>> map;

            try{
                map = getStringListMap();
            }finally {
                // 业务执行完成,释放锁
                String script = "if redis.call('get',KEYS[1]) == ARGV[1]  then return redis.call('del',KEYS[1]) else  return 0 end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script,Long.class),Arrays.asList("lock"),uuid);
                System.out.println("删除分布式锁成功...");
            }
            return map;
        }else{
            System.out.println("抢占分布式锁失败...自旋中...");
            // 抢占失败,自旋
            return getCatalogJsonFromDB();
        }
    }

    private Map<String, List<Catalog2Vo>> getStringListMap() {
        synchronized (this){
            String catalogJson = redisTemplate.opsForValue().get("catalogJson");
            if(StringUtils.isEmpty(catalogJson)){
                //查询所有类目
                System.out.println("查询了数据....");
                //1. 查询所有一级类目
                List<CategoryEntity> level1Category = getLevel1Category();
                // 收集成Map
                Map<String, List<Catalog2Vo>> map = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    // 查询当前类目所属的二级类目
                    List<CategoryEntity> level2 = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
                    List<Catalog2Vo> catalog2Vos = null;
                    if (level2 != null) {
                        catalog2Vos = level2.stream().map(l2 -> {
                            Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), l2.getCatId().toString(), l2.getName(), null);
                            // 查询三级类目
                            List<CategoryEntity> level3 = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                            List<Catalog2Vo.Catalog3List> catelog3Lists = level3.stream().map(l3 -> {
                                Catalog2Vo.Catalog3List catelog3List = new Catalog2Vo.Catalog3List(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                return catelog3List;
                            }).collect(Collectors.toList());
                            catalog2Vo.setCatalog3List(catelog3Lists);
                            return catalog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catalog2Vos;
                }));
                String jsonString = JSON.toJSONString(map);
                redisTemplate.opsForValue().set("catalogJson",jsonString);
                return map;
            }
            Map<String, List<Catalog2Vo>> parseObject = JSON.parseObject(catalogJson, new TypeReference<Map<String, List<Catalog2Vo>>>() {});
            return parseObject;
        }
    }

    @Override
    public List<CategoryEntity> getLevel1Category() {

        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {

        QueryWrapper<CategoryEntity> queryWrapper = new QueryWrapper<>();
  //      queryWrapper.eq("name","骑行运动");
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2.组装成父子的树形结构

        //2.1 找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity,entities));
                    return categoryEntity;
                })
                .sorted((menu1,menu2)->{
                    return (menu1.getSort()==null?0: menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());

        return level1Menus;

    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1、检查当前删除的菜单,是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {

        List<Long> paths = new ArrayList<>();
        List<Long> catelogIds = findParentPath(catelogId,paths);
        Collections.reverse(catelogIds);
        return catelogIds.toArray(new Long[catelogIds.size()]);

    }

    @Transactional
    @Override
    public void updateByIdDeteil(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){

        // 收集当前节点id
        paths.add(catelogId);

        CategoryEntity byId = this.getById(catelogId);

        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    // 递归查找所有菜单的子菜单
    /**
     * 逻辑分析:
     * 第一步:这里先不要看找到子菜单这一步,忽略这一步看代码的话很简单,就是找到当前实体中的children信息并返回
     * 第二步:return categoryEntity.getParentCid() == root.getCatId();
     *       这一步是将当前实体的children数据找到然后return给下面.map
     *       这个时候当前实体的children数据已经找到了,listWithTree()方法会设置给一级分类,这个我们不用管,
     *       这个时候getChildrens(要查找子类数据的父类,所有数据)这个方法已经实现了。
     *       我们关心的是当前实体的children数据该怎么设置
     *       .map(categoryEntity -> {return categoryEntity;}) 这里的categoryEntityChildren就是当前实体的children数据,
     *       所以我们categoryEntityChildren.setChildren(getChildrens(categoryEntityChildren, all));
     *       这样就把当前实体children的children数据设置给当前实体的children了,然后也是迭代完成了,这就不用管了。
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        if(root.getCatId()==17l){
            System.out.println(root);
        }
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
 /**
  * 发现parent_cid和cat_id的判断是用==来判断的。而cat_id的类型的Long的包装类型，是一个引用类型。在用==判断的使用是比较值以及地址。
  * 而Long类型的的-128~127是从数组里面拿的，是基础类型，只是比较值，而128以后的值就是包装类型，值和地址都比较，
  * 一个值为128的parent_id和128的cat_id在进行用==比较的时候由于地址不一样，导致return false。
  * 所以这里应该用equals()方法进行比较，Long类型的eauals()方法是被重写了的，只是比较值的大小，不比较地址。我们把==换成equals()试试效果
  */
                    return categoryEntity.getParentCid().equals(root.getCatId());
                }).map(categoryEntityChildren -> {
                    System.out.println("categoryEntityChildren=="+categoryEntityChildren);
                    if(categoryEntityChildren.getCatId()==128l){
                        System.out.println(categoryEntityChildren);
                    }
                    //1.找到子菜单
                    categoryEntityChildren.setChildren(getChildrens(categoryEntityChildren, all));
                    return categoryEntityChildren;
                }).sorted((menu1, menu2) -> {
                    return (menu1.getSort()==null?0: menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());

        return children;
    }


}